﻿/修改------
package com.kanglefu.activity.account;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.kanglefu.R;
import com.kanglefu.activity.MainTabActivity;
import com.kanglefu.app.App;
import com.kanglefu.cfg.RT;
import com.kanglefu.cfg.Url;
import com.kanglefu.fragment.main.MySelfFragment;
import com.kanglefu.manager.TokenManager;
import com.kanglefu.model.RespBaseModel;
import com.kanglefu.model.resp.RespUserInfo;
import com.kanglefu.model.resp.UserInfo;
import com.kanglefu.utils.ComUtils;
import com.kanglefu.utils.DensityUtil;
import com.kanglefu.utils.LOG;
import com.kanglefu.utils.PreferenceUtils;
import com.kanglefu.utils.ToastUtil;
import com.kanglefu.view.dialog.AlertUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

public class LoginActivity extends com.kanglefu.base.BaseLoadingActivity
		implements OnClickListener {
	@ViewInject(R.id.edit_name)
	private EditText edit_name;
	@ViewInject(R.id.edit_password)
	private EditText edit_password;
	@ViewInject(R.id.tx_register)
	private TextView tx_register;
	@ViewInject(R.id.forget_password)
	private TextView tx_forgetpassword;
	@ViewInject(R.id.bnt_login)
	private Button bnt_login;
	private LinearLayout bntWXLogin;
	Button bnttitleLeft ;
	public static final int FORGETPASSWORDCODE = 10082;
	public static final int REGISTERCODE = 10081;
	public static  final int BUNDPHONE = 888;
	public static final int REQUESTCODE = 798;  // 调用登入的地方 登入回调
	public int isDeviceSkip = 0;
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int wh = msg.what;
			if(1==wh){
		 String opd = 		(String) msg.obj;
		 Bundle bundle = new Bundle();
			bundle.putSerializable("opd", opd);
			Intent intent = new Intent(mCxt, BundPhone.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			intent.putExtras(bundle);
				startActivityForResult(intent, BUNDPHONE);
			}
		};
	};
	
	UMShareAPI  mShareAPI;
	@SuppressLint("ResourceAsColor") @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_login);
		getbunddata();
		setTitleView(LayoutInflater.from(mCxt).inflate(R.layout.title_bar, null));
		bindView();
		//setTitleBarColor(R.color.loginbackgound);
	//	mShareAPI = UMShareAPI.get(LoginActivity.this);
	        mShareAPI = UMShareAPI.get( LoginActivity.this );
	        String rid = JPushInterface.getRegistrationID(getApplicationContext());
			Log.e("tag", "rid="+rid);
			System.out.println("");
			App.pfCfg.setIsLogin(false);
	}

	private void getbunddata() {
		try{
			Bundle extras = getIntent().getExtras();
			if(extras!=null){
				String key = extras.getString("key");
				if("nologin".equals(key)){
					isDeviceSkip = 1;
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	private void bindView() {
		edit_name = (EditText) findViewById(R.id.edit_name);
		edit_name.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		edit_password = (EditText) findViewById(R.id.edit_password);
		tx_register = (TextView) findViewById(R.id.tx_register);
		tx_forgetpassword = (TextView) findViewById(R.id.forget_password);
		bnt_login = (Button) findViewById(R.id.bnt_login);
		bntWXLogin = (LinearLayout) findViewById(R.id.bnt_wx_login);
		// @OnClick(value = { R.id.bnt_login, R.id.bnt_wx_login,
		// R.id.tx_register,
		// R.id.forget_password })
		tx_forgetpassword.setOnClickListener(this);
		tx_register.setOnClickListener(this);
		bnt_login.setOnClickListener(this);
		bntWXLogin.setOnClickListener(this);
		bnttitleLeft = (Button) findViewById(R.id.btn_title_left);
		bnttitleLeft.setOnClickListener(this);
		float density = DensityUtil.getDensity(mCxt);
	}

	private UMAuthListener umAuthListener = new UMAuthListener() {
		 @Override
		    public void onStart(SHARE_MEDIA platform) {
		       //授权开始的回调
		    }
		    @Override
		    public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
		    	/*
				 * 授权成功
				 * */
		    	
				 String  openid = data.get("openid");
				String accessToken = data.get("access_token");
				String  unionid = data.get("unionid");
				App.pfCfg.setLoginOpenId(openid);
				App.pfCfg.setloginAssessToken(accessToken);
				
				
				LOG.v("微信回调成功", "openid="+openid+"&accessToken="+accessToken);
				
				//umAuthListener.onComplete(arg0, arg1, arg2)
				vericationIsBund(openid,accessToken,unionid);
				UMShareAPI.get(getApplicationContext()).deleteOauth(LoginActivity.this, platform, null);
				
		    }

		    @Override
		    public void onError(SHARE_MEDIA platform, int action, Throwable t) {
		    }

		    @Override
		    public void onCancel(SHARE_MEDIA platform, int action) {
		    }
		};
	
	
	private void vericationIsBund(final String openId,final String acessToken,final String unionid) {
		HashMap<String, String> map = new HashMap<String, String>() {
			{
				put("accessToken", acessToken);
				put("openID", openId);
				put("expiryMinutes","30");
				put("unionId", unionid);
			
			}
		};
	//	post(RT.POST_WINYANZ, Url.HOST+"base/baseCustomWechat/info", RespBaseModel.class, null);
		post(RT.POST_WINYANZ, Url.HOST+"base/baseCustomWechat/info", RespBaseModel.class, map);
	}


	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.bnt_login:
			if (CheckInput()) {
				
		HashMap<String, String> map = new HashMap<String, String>() {
				{
					put("expiryMinutes","30");
					put("username", edit_name.getText().toString().trim());
					put("password", edit_password.getText().toString().trim());
				}
			};
			//showLoadingView("加载中...");
			post(RT.POST_LOGIN, Url.HOST + "api/custom/authentication", RespBaseModel.class,
					map);
			}
			break;
		case R.id.bnt_wx_login:
	          mShareAPI.doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
			break;

		case R.id.tx_register:
			Intent intent = new Intent(mCxt, RegisterActivity.class);
			startActivityForResult(intent, REGISTERCODE);
		
			break;
		case R.id.forget_password:// 找回密码
			Intent forget = new Intent(mCxt, ForgetPassword.class);
			startActivityForResult(forget, FORGETPASSWORDCODE);
			break;
		case R.id.btn_title_left:
			if(1==isDeviceSkip){
				Intent intentdevices = new Intent(MainTabActivity.MAINTAB_ACTION);
				Bundle bundledevices = new Bundle();
				bundledevices.putString("temp", MainTabActivity.MAIN_ACTION_HOME);
				intentdevices.putExtras(bundledevices);
				mCxt.sendBroadcast(intentdevices);
			}
			finish();
		default:
			break;
		}
	}
	private boolean CheckInput() {
		if (edit_name.getText().toString().trim().isEmpty()) {
			ToastUtil.showToast(mCxt, "手机号码不能为空");
			return false;
		} else {
			if (!ComUtils.isCellphone(edit_name.getText().toString().trim())) {
				ToastUtil.showToast(mCxt, "请输入正确的手机号码");
				return false;
			}
		}
	

		if (edit_password.getText().toString().trim().isEmpty()) {
			ToastUtil.showToast(mCxt, "密码不能为空");
			return false;
			
		} else {
			if (!ComUtils.isPassword(edit_password.getText().toString().trim())) {
				ToastUtil.showToast(mCxt, "请输入6-25位的英文或数字");
				return false;
			}
		}
		return true;
	}

	@Override
	protected void onReqStart(String action) {
		// TODO Auto-generated method stub
		super.onReqStart(action);
		showOptDialog("");
	}

	@Override
	protected void onSuccess(RespBaseModel resp) {
		// TODO Auto-generated method stub
		super.onSuccess(resp);
		dismissLoadingView();
		//disOptDialog();
		disOptDialog();

		String action = resp.action;
		
		if (RT.POST_LOGIN.equals(action)) {
			//System.out.println(resp.respStr);
			
			try {
				JSONObject object = new JSONObject(resp.respStr);
				int code = object.getInt("code");
				if (1 == code) {
					JSONObject obj = object.optJSONObject("obj");
					String token = obj.optString("token");
					PreferenceUtils.putString("token", token);
					Log.e("token", token);
					App.pfCfg.setToken(token);
					App.pfCfg.setIsLogin(true);
				  TokenManager.getInstance().startTimer();
					post(RT.POST_USERDATA, Url.HOST + "center/myInfo",
							RespUserInfo.class, null);
				} else if (0 == code) {
					String msg = object.getString("msg");
					ToastUtil.showToast(mCxt, msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(RT.POST_WINYANZ.equals(action)){
			try{
				String data = resp.respStr;
				JSONObject object = new JSONObject(data);
				int code = object.optInt("code", 0);
				if(code==1){
					final JSONObject jsonmodel = object.getJSONObject("obj");
					int optInt = jsonmodel.optInt("sign");
					if(1==optInt){
						String token = jsonmodel.optString("token");
						PreferenceUtils.putString("token", token);
						App.pfCfg.setIsLogin(true);
					/*	Log.e("tag", resp.respStr);
						setResult(MySelfFragment.LoginSusessTag);
						finish();*/
						post(RT.POST_USERDATA, Url.HOST + "center/myInfo",
								RespUserInfo.class, null);
					}else{
						try{
						LOG.v("其实我想问来了这里没有", "表示道理是是没额问题的");
									String opd  = 	jsonmodel.optString("opd");
									LOG.v("其实我想问来了这里没有", "表示道理是jsonmodel.optString(是没额问题的");
								/*		*/
										Message message = new Message();
										message.what = 1;
										message.obj = opd;
										handler.sendMessage(message);
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}else{
					String msg = object.optString("msg");
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
			
		}else if (RT.POST_USERDATA.equals(action)) {
			try{
			RespUserInfo userInfo = (RespUserInfo) resp;
			if (1 == userInfo.code) {
				Log.e("tag", resp.respStr);
				UserInfo info = userInfo.obj;
				System.out.println(info);
				App.pfCfg.setLoginPhone(info.mobile.trim());
				App.pfCfg.setLoginUserId(info.userId);
				App.pfCfg.setLoginUserName(info.name);
				App.pfCfg.setLoginNickName(info.nickname);
				if ("1".equals(info.sex)) {
					App.pfCfg.setLoginSex("女");
				} else if ("2".equals(info.sex)) {
					App.pfCfg.setLoginSex("男");
				} else if ("0".equals(info.sex)) {
					App.pfCfg.setLoginSex("保密");
				}
				App.pfCfg.setLoginPhone(info.mobile);
				App.pfCfg.setLoginIdCard(info.idcard);
				App.pfCfg.setLoginHeadimgUrl(info.headimgurl);
				setResult(1);
			finish();
			}else {
				
			}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}






	@Override
	protected void onFailure(String action,
			com.lidroid.xutils.exception.HttpException error, String msg) {
		super.onFailure(action, error, msg);
		disOptDialog();
	}

/*	@Override
	protected void onFailure(String action, HttpException error, String msg) {
		// TODO Auto-generated method stub
		super.onFailure(action, error, msg);
		dismissLoadingView();
		disOptDialog();
		if(RT.POST_WINYANZ.equals(action)){
			LOG.v("失败"+RT.POST_WINYANZ, msg);
			ToastUtil.showToast(mCxt, msg+"调用微信接口失败");
		}
	}*/

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

		if (REGISTERCODE == requestCode) {
			if (resultCode == 1) {
				edit_name.setText(App.pfCfg.getLoginPhone());
				edit_password.setText(App.pfCfg.getLoginUserPwd());
				bnt_login.performClick();

			}

		} else if (FORGETPASSWORDCODE == requestCode) {
			if (resultCode == 1) {
				edit_name.setText(App.pfCfg.getLoginPhone());
				edit_password.setText(App.pfCfg.getLoginUserPwd());
				bnt_login.performClick();
			}
		}else if(requestCode==BUNDPHONE){
			setResult(MySelfFragment.LoginSusessTag);
			finish();
		}
	}
	
	
	public boolean dispatchKeyEvent(KeyEvent event) {
		LogUtils.e("dispatchKeyEvent(KeyEvent event)");
		// 按下键盘上返回按钮
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_UP) {
			if(1==isDeviceSkip){
				Intent intentdevices = new Intent(MainTabActivity.MAINTAB_ACTION);
				Bundle bundledevices = new Bundle();
				bundledevices.putString("temp", MainTabActivity.MAIN_ACTION_HOME);
				intentdevices.putExtras(bundledevices);
				mCxt.sendBroadcast(intentdevices);
				finish();
			//	return true;
			}

			

		}
		return super.dispatchKeyEvent(event);
	}
}
